import collections
import os
import sys

import xlsxwriter
from moviepy.editor import VideoFileClip


class File_excel:
    '''所有文件必须同级'''

    def __init__(self, file_dir):
        self.file_dir = file_dir

    def get_path_list(self, file_dir):
        pathss = []
        for root, dirs, files in os.walk(file_dir):
            path = [os.path.join(root, name) for name in files]
            if path:
                pathss.extend(path)
        return pathss

    def path_element_to_dict(self, path_list):
        path_list = [{'name': path.split('\\')[-1], 'path': path, 'time': self.get_file_time(path)} for path in
                     path_list]
        return path_list

    def get_same_element_list(self, column_path):
        # 获取每组列表中的相同元素的数量字典组成的列表
        dic_list = []
        for column in column_path:
            dic_list.append(collections.Counter(column_path[column]))
        return dic_list

    def convert_dict_list(self, dic_list):
        # 改成[{'k':{},'k2':{}},{'k':{},'k2':{}}]
        lis_list = []
        for dic in dic_list:
            da_dict = {}
            for (k, v) in dict(dic).items():
                da_dict[k] = {'num': v, 'time': 0}
            lis_list.append(da_dict)
        return lis_list

    def get_path_level(self, path):
        level = len(path.split(self.file_dir)[1].split('\\')) - 1
        return level

    def convert_transverse_vertical(self, level, path_list):
        column_path = {i: [] for i in range(level - 1)}
        for path in path_list:
            for i in range(level - 1):
                column_path[i].append(path[i])
        return column_path

    def init_work_sheet(self):
        f = xlsxwriter.Workbook('course.xlsx')  # 创建excel文件
        worksheet = f.add_worksheet('course')  # 括号内为工作表表名
        return worksheet, f

    def create_headings(self, headings, level):
        for i in range(level - 1):
            headings.insert(0, '{}级目录'.format(level - 1 - i))
            headings.append('{}级时长'.format(level - 1 - i))
        headings.append('进度')
        return headings

    def get_file_time(self, path):
        clip = VideoFileClip(path)
        size = clip.duration
        clip.reader.close()
        clip.audio.reader.close_proc()

        return size

    def convert_time(self, second):
        M, H = 60, 60 ** 2
        if second < M:
            tim_srt = u'00:00:%02d' % second
        if second < H:
            tim_srt = u'00:%02d:%02d' % (int(second / M), int(second % M))
        else:
            hour = int(second / H)
            mine = int(second % H / M)
            second = int(second % H % M)
            tim_srt = u'%s:%02d:%02d' % (hour, mine, second)
        return tim_srt

    def run(self):
        paths = self.get_path_list(self.file_dir)
        # print(paths)
        # 获取分隔好的列表
        path_list = [path.split(self.file_dir + '\\')[1].split('\\') for path in paths]
        # 获取层级深度
        level = self.get_path_level(paths[0])
        # 横列数组变成纵列
        column_path = self.convert_transverse_vertical(level, path_list)

        # 获取每组列表中的相同元素的数量字典组成的列表
        dic_list = self.get_same_element_list(column_path)

        # 改成[[{'k':{},'k2':{}}],[{'k':{},'k2':{}}]]
        lis_list = self.convert_dict_list(dic_list)

        # 最底层文件name和时间数据,上级分隔
        paths = [{"name": path.split('\\')[-1], 'path': path.split(self.file_dir + '\\')[1].split('\\')[0:-1],
                  'time': self.get_file_time(path)} for path in paths]

        worksheet, f = self.init_work_sheet()

        # 构造excel的header
        headings = self.create_headings(['文件', '时长'], level)
        worksheet.write_row('A1', headings)

        # 写入文件和文件自带时长并计算目录时长
        last_level_row = 1
        for path in paths:
            worksheet.write_string(last_level_row, level - 1, path['name'])
            worksheet.write_string(last_level_row, level, self.convert_time(path['time']))
            for lis in lis_list:
                for i in range(level - 1):
                    k = path['path'][i]
                    if k in lis.keys():
                        lis[k]['time'] += path['time']

            last_level_row += 1

        for lis in lis_list:
            i = lis_list.index(lis)
            prev_row = 1
            for (k, v) in lis.items():
                if v['num'] == 1:
                    worksheet.write_string(prev_row, i, k)
                    worksheet.write_string(prev_row, level + (level - i - 1), self.convert_time(v['time']))

                else:
                    worksheet.merge_range(prev_row, i, prev_row + v['num'] - 1, i, k)
                    worksheet.merge_range(prev_row, level + (level - i - 1), prev_row + v['num'] - 1,
                                          level + (level - i - 1),
                                          self.convert_time(v['time']))
                prev_row += v['num']
        f.close()


if __name__ == "__main__":
    path = sys.argv[1]
    file_excel = File_excel(path)
    file_excel.run()
